package com.wing.productionPlan.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.enums.ProductEnum;
import com.wing.common.utils.JsonResult;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.request.CustomerProductCatalogForm;
import com.wing.enterprise.product.model.request.ExternalProductForm;
import com.wing.enterprise.product.model.request.ProductReviewAddForm;
import com.wing.productionPlan.dao.DemandPlanDao;
import com.wing.productionPlan.dao.RequirePlanDao;
import com.wing.productionPlan.enumeration.AuditStatusEnum;
import com.wing.productionPlan.enumeration.OperationEnumType;
import com.wing.productionPlan.model.entity.*;
import com.wing.productionPlan.model.response.CustomerCataLogVo;
import com.wing.productionPlan.model.response.DemandPlanVO;
import com.wing.productionPlan.model.response.RequirePlanVO;
import com.wing.web.excel.DemandPlanExcelln;
import com.wing.web.excel.RequirePlanExcelln;

import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;


/**
 * 需求计划表-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class RequirePlanServiceImpl extends ServiceImpl<RequirePlanDao, RequirePlan> implements RequirePlanService {

    @Autowired
    RequirePlanItermService requirePlanItermService;

    @Autowired
    RequirePlanIProductService requirePlanIProductService;


    /**
     * 分页查询任务列表
     *
     * @param pg
     * @param map
     * @return
     */
    @Override
    public Page<RequirePlanVO> pageList4app(Page<RequirePlanVO> pg, Map map) {
        List<RequirePlanVO> vos = this.baseMapper.pageList4app(pg, map);
        pg.setRecords(vos);
        return pg;
    }

    @Override
    public RequirePlanVO get4appById(Long id) {
        return this.baseMapper.get4appById(id);
    }

    @Override
    @Transactional
    public void importExcel(List<RequirePlanExcelln> list) {
        try {
            addExcel(list);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    /**
     * 手动保存
     * @param requirePlan
     */
    @Transactional
    @Override
    public JsonResult savePlan(RequirePlan requirePlan) {

        requirePlan.setCreator(JwtUtils.getLoginUserId());
        requirePlan.setModifier(JwtUtils.getLoginUserId());
        requirePlan.setCreateTime(LocalDateTime.now());
        requirePlan.setCreatorName(JwtUtils.getLoginUsername());

        try {
            requirePlan.setRequirePlanNumber(String.valueOf(randomNumber()));
            requirePlan.setContainedMaterialCount(requirePlan.getRequirePlanItemList().size());
            requirePlan.setSaveSourceCode(OperationEnumType.ADD.getCode());
            requirePlan.setSaveSource(OperationEnumType.ADD.getData());
            requirePlan.setAuditStatus(AuditStatusEnum.APPROVED.getCode());
            requirePlan.setAuditPeople(JwtUtils.getLoginUsername());
            save(requirePlan);


            List<RequirePlanItem> requirePlanItemList = requirePlan.getRequirePlanItemList();
            for (RequirePlanItem requirePlanItem : requirePlanItemList) {
                requirePlanItem.setPlanId(requirePlan.getId());
                requirePlanItem.setPlanItermNumber(generateCode());
                requirePlanItem.setRequirePlanNumber(requirePlan.getRequirePlanNumber());
                requirePlanItem.setSaveSourceCode(OperationEnumType.ADD.getCode());
                requirePlanItem.setSaveSource(OperationEnumType.ADD.getData());
                requirePlanItem.setCreatorName(JwtUtils.getLoginUsername());
                requirePlanItem.setCreator(JwtUtils.getLoginUserId());
                requirePlanItem.setRequirePlanNumber(requirePlan.getRequirePlanNumber());
                requirePlanItem.setFactoryName(requirePlan.getFactoryName());
                requirePlanItem.setPlantCode(requirePlan.getPlantCode());
            }

            if(requirePlanItemList.size()>0){
                //requirePlanItermService.saveBatch(requirePlanItemList);
                //保存计划产品信息
                for (RequirePlanItem requirePlanItem : requirePlanItemList) {
                    String plantCode = requirePlanItem.getPlantCode();
                    String materialCode = requirePlanItem.getMaterialCode();
                    String receiveMouthDate = requirePlanItem.getReceiveMouthDate();

                    // 创建 LambdaQueryWrapper
                    LambdaQueryWrapper<RequirePlanItem> wrapper1 = Wrappers.<RequirePlanItem>lambdaQuery()
                            .eq(RequirePlanItem::getPlantCode, plantCode)
                            .eq(RequirePlanItem::getMaterialCode, materialCode)
                            .eq(RequirePlanItem::getPlanId,  requirePlan.getId())
                            .eq(RequirePlanItem::getReceiveMouthDate, receiveMouthDate);
                    RequirePlanItem requirePlanItermServiceOne = requirePlanItermService.getOne(wrapper1);
                    if(requirePlanItermServiceOne!=null){
                        Long id = requirePlanItermServiceOne.getId();
                        BeanUtil.copyProperties(requirePlanItem, requirePlanItermServiceOne,true);
                        requirePlanItermServiceOne.setId(id);
                        requirePlanItermService.updateById(requirePlanItermServiceOne);
                    }else{
                        requirePlanItermService.save(requirePlanItem);
                    }


                    RequirePlanProduct requirePlanProduct=new RequirePlanProduct();
                    requirePlanProduct.setPlantCode(plantCode);
                    requirePlanProduct.setMaterialCode(materialCode);
                    requirePlanProduct.setReceiveMouthDate(receiveMouthDate);

                    // 创建 LambdaQueryWrapper
                    LambdaQueryWrapper<RequirePlanProduct> wrapper = Wrappers.<RequirePlanProduct>lambdaQuery()
                            .eq(RequirePlanProduct::getPlantCode, plantCode)
                            .eq(RequirePlanProduct::getMaterialCode, materialCode)
                            .eq(RequirePlanProduct::getReceiveMouthDate, receiveMouthDate);
                    RequirePlanProduct requirePlanProduct1 = requirePlanIProductService.getOne(wrapper);
                    if(requirePlanProduct1!=null){
                        Long id = requirePlanProduct1.getId();
                        //TODO copy对应同字段内容
                        BeanUtil.copyProperties(requirePlanItem, requirePlanProduct1,true);
                        requirePlanProduct1.setId(id);
                        requirePlanIProductService.updateById(requirePlanProduct1);
                        generateInnerProductInfo(requirePlanProduct1);
                    }else{
                        //TODO copy对应同字段内容
                        BeanUtil.copyProperties(requirePlanItem, requirePlanProduct,true);
                        requirePlanIProductService.save(requirePlanProduct);
                        generateInnerProductInfo(requirePlanProduct);
                    }
                 }

         /*   if(requirePlanProductList.size()>0){
                requirePlanIProductService.saveBatch(requirePlanProductList);
                return JsonResult.success("添加成功");
            }*/
            }
        }catch (Exception e){
            e.printStackTrace();
            return JsonResult.fail("添加失败");
        }

        return JsonResult.success("添加成功");
    }


    /**
     * 添加excel
     * @param list
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void addExcel(List<RequirePlanExcelln> list) {

        try {
            //获取到所有导入行数据   单词导入为一次计划
            RequirePlan requirePlan=new RequirePlan();
            requirePlan.setRequirePlanNumber(String.valueOf(randomNumber()));
            requirePlan.setContainedMaterialCount(list.size());

            requirePlan.setPlantCode(list.get(0).getPlantCode());
            requirePlan.setFactoryName(list.get(0).getFactoryName());
            //TODO 采购组织和采购名称可能没有 都存对应详情去了
            requirePlan.setPurchaseTissue(list.get(0).getPurchaseTissue());
            requirePlan.setPurchaseTissueName(list.get(0).getPurchaseTissueName());
            /*    requirePlan.setReceiveMouthDate(list.get(0).getReceiveMouthDate());*/
            requirePlan.setSaveSourceCode(OperationEnumType.IMPORT.getCode());
            requirePlan.setSaveSource(OperationEnumType.IMPORT.getData());
            requirePlan.setAuditStatus(AuditStatusEnum.APPROVED.getCode());
            requirePlan.setCreatorName(JwtUtils.getLoginUsername());
            requirePlan.setCreator(JwtUtils.getLoginUserId());
            save(requirePlan);


            List<RequirePlanItem> requirePlanItemList=new ArrayList<>();
            //处理导入的每一条数据  属于该次导入计划 planItermNumber
            for (RequirePlanExcelln requirePlanExcelln : list) {
                RequirePlanItem requirePlanItem = new RequirePlanItem();
                requirePlanItem.setPlanId(requirePlan.getId());
                requirePlanItem.setPlanItermNumber(generateCode());
                //TODO copy对应同字段内容
                BeanUtil.copyProperties(requirePlanExcelln, requirePlanItem,true);
                requirePlanItem.setRequirePlanNumber(requirePlan.getRequirePlanNumber());
                requirePlanItem.setSaveSourceCode(OperationEnumType.IMPORT.getCode());
                requirePlanItem.setSaveSource(OperationEnumType.IMPORT.getData());
                requirePlanItem.setCreatorName(JwtUtils.getLoginUsername());
                requirePlanItem.setCreator(JwtUtils.getLoginUserId());
                requirePlanItemList.add(requirePlanItem);
            }

            if(requirePlanItemList.size()>0){
                //requirePlanItermService.saveBatch(requirePlanItemList);
                //保存计划产品信息
                for (RequirePlanItem requirePlanItem : requirePlanItemList) {
                    String plantCode = requirePlanItem.getPlantCode();
                    String materialCode = requirePlanItem.getMaterialCode();
                    String receiveMouthDate = requirePlanItem.getReceiveMouthDate();

                    // 创建 LambdaQueryWrapper
                    LambdaQueryWrapper<RequirePlanItem> wrapper1 = Wrappers.<RequirePlanItem>lambdaQuery()
                            .eq(RequirePlanItem::getPlantCode, plantCode)
                            .eq(RequirePlanItem::getMaterialCode, materialCode)
                            .eq(RequirePlanItem::getPlanId, requirePlan.getId())
                            .eq(RequirePlanItem::getReceiveMouthDate, receiveMouthDate);
                    RequirePlanItem requirePlanItermServiceOne = requirePlanItermService.getOne(wrapper1);
                    if(requirePlanItermServiceOne!=null){
                        Long id = requirePlanItermServiceOne.getId();
                        BeanUtil.copyProperties(requirePlanItem, requirePlanItermServiceOne,true);
                        requirePlanItermServiceOne.setId(id);
                        requirePlanItermService.updateById(requirePlanItermServiceOne);
                    }else{
                        requirePlanItermService.save(requirePlanItem);
                    }


                    RequirePlanProduct requirePlanProduct=new RequirePlanProduct();
                    requirePlanProduct.setPlantCode(plantCode);
                    requirePlanProduct.setMaterialCode(materialCode);
                    requirePlanProduct.setReceiveMouthDate(receiveMouthDate);

                    // 创建 LambdaQueryWrapper
                    LambdaQueryWrapper<RequirePlanProduct> wrapper = Wrappers.<RequirePlanProduct>lambdaQuery()
                            .eq(RequirePlanProduct::getPlantCode, plantCode)
                            .eq(RequirePlanProduct::getMaterialCode, materialCode)
                            .eq(RequirePlanProduct::getReceiveMouthDate, receiveMouthDate);
                    RequirePlanProduct requirePlanProduct1 = requirePlanIProductService.getOne(wrapper);
                    if(requirePlanProduct1!=null){
                        Long id = requirePlanProduct1.getId();
                        //TODO copy对应同字段内容
                        BeanUtil.copyProperties(requirePlanItem, requirePlanProduct1,true);
                        requirePlanProduct1.setId(id);
                        requirePlanIProductService.updateById(requirePlanProduct1);

                        //生成外部产品信息
                        generateInnerProductInfo(requirePlanProduct1);
                    }else{
                        //TODO copy对应同字段内容
                        BeanUtil.copyProperties(requirePlanItem, requirePlanProduct,true);
                        requirePlanIProductService.save(requirePlanProduct);
                        //生成外部产品信息
                        generateInnerProductInfo(requirePlanProduct);

                    }
               }
          /*  if(requirePlanProductList.size()>0){

                requirePlanIProductService.saveBatch(requirePlanProductList);
            }*/

            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Autowired
    EnterpriseClient enterpriseClient;

    public void generateInnerProductInfo(RequirePlanProduct requirePlanProduct) {
        //判断内部产品有咩有
        Long externalProductId= baseMapper.selExternalProductId(requirePlanProduct.getMaterialCode());
        Long customerId = baseMapper.selCustomerId(requirePlanProduct.getFactoryName());

        if(externalProductId==null || externalProductId==0L){
             // 添加关联外部  	com_external_product  sel_customer_product_catalog

            CustomerProductCatalogForm customerProductCatalogForm=new CustomerProductCatalogForm();
            ExternalProductForm externalProductForm=new ExternalProductForm();

            externalProductForm.setCreatorName(JwtUtils.getLoginUsername());
            externalProductForm.setCreator(JwtUtils.getLoginUserId());

            externalProductForm.setCusSkuCode(requirePlanProduct.getMaterialCode());
            externalProductForm.setCusProductName(requirePlanProduct.getMaterialCode());
            externalProductForm.setCusProductSpec(requirePlanProduct.getMaterialDescribe());

            customerProductCatalogForm.setCustomerId(customerId);

            customerProductCatalogForm.setExternalProductForm(Arrays.asList(externalProductForm));
            enterpriseClient.addProduct(customerProductCatalogForm);
        }



        Long outerProductInfo = baseMapper.selIsInnerOuterProductInfo(requirePlanProduct.getMaterialCode());
        if(outerProductInfo==null || outerProductInfo==0L){
            generateProductPreview(requirePlanProduct,customerId,externalProductId);
        }

    }


   public void generateProductPreview(RequirePlanProduct requirePlanProduct, Long customerId, Long externalProductId){

       //生成对应评审任务 222222222
       ProductReviewAddForm productReviewAddForm=new ProductReviewAddForm();

       productReviewAddForm.setCustomerId(customerId);
    /*   if(externalProductId!=null && externalProductId!=0L){
           productReviewAddForm.setCusSkuCode(externalProductId.toString());
       }*/
       productReviewAddForm.setCusSkuCode(requirePlanProduct.getMaterialCode());
       productReviewAddForm.setCusProductCategory(requirePlanProduct.getMaterialType());
       //没 取得编码
       productReviewAddForm.setCusProductName(requirePlanProduct.getMaterialCode());
       productReviewAddForm.setCusProductSpec(requirePlanProduct.getMaterialDescribe());
       productReviewAddForm.setCusProductUnit(requirePlanProduct.getMaterialUnit());
       productReviewAddForm.setCusProductCount(requirePlanProduct.getDemandQuantity());
       if(StringUtils.isNotEmpty(requirePlanProduct.getPlanReceiveTime())){
           // 定义与字符串格式相匹配的格式化器
           DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

           try {
               // 使用格式化器解析字符串为 LocalDateTime 对象
               LocalDateTime localDateTime = LocalDateTime.parse(requirePlanProduct.getPlanReceiveTime(), formatter);

               productReviewAddForm.setReviewEndTime(localDateTime);
               productReviewAddForm.setPlanGivenTime(localDateTime);
           } catch (DateTimeParseException e) {

           }

       }
       //todo 部门目前写死的
       productReviewAddForm.setDepartmentId(9L);
       productReviewAddForm.setPostId(9L);
       productReviewAddForm.setPostName("仓管");
       productReviewAddForm.setReviewProcessId(1L);

       productReviewAddForm.setCustomerName(requirePlanProduct.getFactoryName());

       productReviewAddForm.setCreator(JwtUtils.getLoginUserId());

       externalProductId= baseMapper.selExternalProductId(requirePlanProduct.getMaterialCode());
       JsonResult result= enterpriseClient.getOutProductId(requirePlanProduct.getMaterialCode());
       if(result.getData()!=null){
           externalProductId=Long.valueOf(result.getData().toString());
       }
       //todo 在加一个产品ID
       productReviewAddForm.setExtProductId(externalProductId);
       enterpriseClient.addProductReview(productReviewAddForm);
   }



    public int randomNumber() {
        int randomNumber = ThreadLocalRandom.current().nextInt(10000000, 100000000);
        return randomNumber;
    }

    private static final String PREFIX = "XQ";
    private static final int RANDOM_NUMBER_LENGTH = 3; // 随机数长度
    private static final Random random = new Random();

    /**
     * 生成指定格式的代码：XQ+年月日时分秒+随机数字
     *
     * @return 格式化的代码字符串
     */
    public static String generateCode() {
        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        // 将当前日期时间格式化为字符串
        String dateTimeStr = now.format(formatter);
        // 生成随机数
        String randomNumber = String.format("%0" + RANDOM_NUMBER_LENGTH + "d", random.nextInt((int)Math.pow(10, RANDOM_NUMBER_LENGTH)));
        // 拼接成最终结果
        return PREFIX + dateTimeStr + randomNumber;
    }




}

